package com.github.aloxc.plugin.restplus.listener;

import com.github.aloxc.plugin.restplus.common.ServiceHelper;
import com.github.aloxc.plugin.restplus.entity.Group;
import com.github.aloxc.plugin.restplus.entity.Sort;
import com.github.aloxc.plugin.restplus.i18n.I18Bundle;
import com.github.aloxc.plugin.restplus.navigation.action.RestServiceItem;
import com.github.aloxc.plugin.restplus.navigator.RestServiceDetail;
import com.github.aloxc.plugin.restplus.navigator.RestServiceProject;
import com.github.aloxc.plugin.restplus.navigator.RestServiceStructure;
import com.github.aloxc.plugin.restplus.popup.PopupBalloon;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import jxl.SheetSettings;
import jxl.Workbook;
import jxl.write.*;
import jxl.write.biff.RowsExceededException;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import static com.github.aloxc.plugin.restplus.popup.PopupBalloon.NORMAL;

/**
 * 导出所有url
 *
 * @author leero
 */
public class OutputListener extends MouseAdapter {
    private RestServiceDetail myRestServiceDetail;

    public OutputListener(RestServiceDetail myRestServiceDetail) {

        this.myRestServiceDetail = myRestServiceDetail;
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        super.mouseClicked(e);
        FileNameExtensionFilter filter = new FileNameExtensionFilter("*.xlsx", "xlsx");
        JFileChooser fc = new JFileChooser();
        fc.setFileFilter(filter);
        fc.setMultiSelectionEnabled(false);
        int result = fc.showSaveDialog(null);
        String filePath = null;
        if (result == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            if (!file.getPath().endsWith(".xlsx")) {
                filePath = file.getPath() + ".xlsx";
                file = new File(filePath);
            }
            WritableWorkbook wwb;
            FileOutputStream fos = null;
            try {
                if (!file.exists()) {//文件不存在 则创建一个
                    file.createNewFile();
                }
                fos = new FileOutputStream(file);
                wwb= Workbook.createWorkbook(fos);
                WritableSheet sheet = wwb.createSheet(I18Bundle.getMessage("com.github.aloxc.plugin.restplus.toolbar.output.sheet.text"), 0);
                List<RestServiceProject> restServiceProjects = ServiceHelper.buildRestServiceProjectListUsingResolver(myRestServiceDetail.getProject());
                restServiceProjects = RestServiceStructure.group(restServiceProjects, Group.MODULE, Sort.ASC);
                boolean first = true;
                WritableCellFormat titleFormat = new WritableCellFormat();
                titleFormat.setBackground(Colour.ORANGE);
//                titleFormat.setFont(new FontRecord());
                Label name = new Label(0, 0, "name");
                Label description = new Label(1, 0, "description");
                Label url = new Label(2, 0, "url");
                name.setCellFormat(titleFormat);
                description.setCellFormat(titleFormat);
                url.setCellFormat(titleFormat);
                sheet.addCell(name);
                sheet.addCell(description);
                sheet.addCell(url);
                sheet.setColumnView(0,30);
                sheet.setColumnView(1,50);
                sheet.setColumnView(2,150);

                int row = 0;
                for(RestServiceProject p: restServiceProjects){
                    first = true;
                    for(RestServiceItem item : p.getServiceItems()){
                        row++;
                        if(first){
                            sheet.addCell(new Label(0,row,p.getName()));
                            first = false;
                        }
                        sheet.addCell(new Label(1,row,item.getDescription()));
                        sheet.addCell(new Label(2,row,item.getUrl()));
                    }
                }
                SheetSettings ss =  sheet.getSettings();//设置sheet表格式
                ss.setVerticalFreeze(1);
                wwb.write();
                wwb.close();
                fos.flush();
                final String __filePath = filePath;
                ApplicationManager.getApplication().invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        JBPopupFactory factory = JBPopupFactory.getInstance();
                        factory.createHtmlTextBalloonBuilder(
                                String.format(I18Bundle.getMessage("com.github.aloxc.plugin.restplus.toolbar.output.pop.text"),__filePath,__filePath)
                                , null, NORMAL, null)
                                .setFadeoutTime(50000)
                                .createBalloon()
                                .show(factory.guessBestPopupLocation((JComponent) e.getComponent()), Balloon.Position.above);
                    }
                });
            } catch (IOException ex) {
                ex.printStackTrace();
            } catch (RowsExceededException ex) {
                ex.printStackTrace();
            } catch (WriteException ex) {
                ex.printStackTrace();
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException ioe) {
                        ioe.printStackTrace();
                    }
                }
            }
        }
    }
}
